<template>
  <div class="component data-tree">
    <template v-for="node of data">
      <data-tree-node v-if="node" :key="node.id" :data="node"></data-tree-node>
    </template>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { Prop, Watch, Emit } from "vue-property-decorator";
import Component from "vue-class-component";
import DataTreeNode from "~/components/common/data-tree-node.vue";
import { EditType } from "~/config/enum.framework";

@Component({
  name: "data-tree",
  components: {
    DataTreeNode
  }
})
export default class DataTree extends Vue {
  private nodeMap = new Map<DataTreeNode, any>();

  // 当前选择项
  private currentNode;

  // 数据列表
  @Prop({
    default: () => []
  })
  private data: any[];

  // 属性参数
  @Prop({
    default: () => { },
    type: Object
  })
  private props: any;

  // 是否显示checkbox
  @Prop({
    default: false,
    type: Boolean
  })
  private showCheckbox: boolean;

  @Prop({
    type: Boolean,
    default: false
  })
  private showEdit: boolean

  @Prop({
    type: Array,
    default: () => [EditType.ADD, EditType.MODIFY, EditType.DELETE]
  })
  private editConfig: number[]

  @Prop({
    type: Function
  })
  private loadData: (data) => Promise<object>;

  public get propsObject() {
    let propObj = {
      title: "title"
    }
    if (this.props) {
      propObj = { ...propObj, ...this.props }
    }
    return propObj
  }

  public registerNode(node, data) {
    this.nodeMap.set(node, data);
  }


  /**
   * 获取当前选中项
   */
  public get selected() {
    return this.currentNode;
  }

  /**
   * 选择当前选中项
   */
  public set selected(node) {
    if (this.currentNode !== node) {
      // 清空历史选中项
      if (this.currentNode) {
        this.currentNode.selected = false;
      }
      this.currentNode = node;
      this.emitSelectChange(node.data);
    }
  }

  /**
   * 获取选中key
   */
  public getCheckedKeys() {
    return Array.from(this.nodeMap.entries())
      .filter(([node, data]) => node.checked)
      .map(([node, data]) => data.id);
  }

  /**
   * 展开树的第一层节点
   */
  public expandedFirstNode() {
    const it = Array[0] || []
    const key = it[0] || {}
    key.expanded = true
  }

  @Watch("data")
  private onDataChange(data) { }

  @Emit("select-change")
  private emitSelectChange(data) { }

  @Emit("current-checked-change")
  private emitCurrentCheckedChange(id, value) { }

  @Emit('edit')
  private emitEdit(data) { }

  @Emit('add')
  private addEdit(data) { }

  @Emit('delete')
  private deleteEdit(data) { }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
